﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Management;
using Microsoft.Win32;


namespace FlexminHost
{
	[RunInstaller(true)]
	public partial class ProjectInstaller : Installer
	{
		public ProjectInstaller()
		{
			InitializeComponent();

			RegistryKey ckey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\CurrentControlSet\Services\Flexmin", true);

			if (ckey != null)
			{
				if (ckey.GetValue("Type") != null)
				{
					ckey.SetValue("Type", ((int)ckey.GetValue("Type") | 256));
				}

				ckey.SetValue("ObjectName", "LocalSystem");
			}			
		}

		public override void Install(IDictionary stateSaver)
		{
			base.Install(stateSaver);
			ServiceController servController = new ServiceController(this.serviceInstaller1.ServiceName);
			try
			{
				servController.Start();
			}
			catch
			{
				// TODO: Error logging
			}
		}

		private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
		{
			ConnectionOptions coOptions = new ConnectionOptions();
			coOptions.Impersonation = ImpersonationLevel.Impersonate;

			ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
			mgmtScope.Connect();

			ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + serviceInstaller1.ServiceName +"'");

			ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
			InParam["DesktopInteract"] = true;

			ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
		}
	}
}
